<template>
  <view class="exhibition-page">
    <!-- 自定义导航栏 -->
    <custom-navbar
      :title="'展品'"
      :background-color="'#FFFFFF'"
    ></custom-navbar>

    <!-- 分类筛选栏 -->
    <view class="category-filter">
      <scroll-view
        scroll-x="true"
        class="category-scroll"
        :scroll-into-view="'cate-' + activeCategory"
        scroll-with-animation
      >
        <view
          v-for="(item, index) in categories"
          :key="index"
          :id="'cate-' + item.galleryId"
          class="category-item"
          :class="{ active: activeCategory === item.galleryId }"
          @click="changeCategory(item.galleryId)"
        >
          {{ item.galleryName }}
        </view>
      </scroll-view>
    </view>

    <!-- 标本展示列表 -->
    <scroll-view
      class="specimen-list"
      scroll-y
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherpulling="onPulling"
      @refresherrefresh="onRefresh"
      @refresherrestore="onRestore"
      @refresherabort="onAbort"
    >
      <view class="specimen-grid">
        <view
          v-for="(item, index) in specimens"
          :key="index"
          class="specimen-card"
          @click="navigateToDetail(item)"
        >
          <image class="specimen-image" :src="item.exhibitImage"></image>
          <view class="specimen-info">
            <text class="specimen-title">{{ item.exhibitName }}</text>
            <text class="specimen-desc">{{ item.exhibitDesc }}</text>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state">
        <text v-if="isLoading">正在加载更多...</text>
        <text v-else-if="hasMore === false">已经到底了~</text>
      </view>
    </scroll-view>

    <!-- 悬浮筛选按钮 -->
    <view class="floating-btn" @click="showFilter">
      <uni-icons type="filter" size="24" color="#FFFFFF"></uni-icons>
    </view>

    <!-- 底部标签栏 -->
    <tab-bar :current="1"></tab-bar>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import CustomNavbar from "@/components/custom-navbar/index.vue";
import TabBar from "@/components/tab-bar/index.vue";
import PlaceholderImage from "@/components/placeholder-image/index.vue";
import { request } from "@/utils/request";

// 展览区接口
const reqGalleries = () => {
	return request({
	  url: "/home/galleries",
	  method: "get",
	})
}

// 展览区展品数据接口
const reqExhibits = (params) => {
	return request({
		url: "/gallery/exhibits",
		method: "get",
		params: params
	})
}

// 筛选分类
const categories = ref([]);

// 当前选中分类
const activeCategory = ref(1);

// 标本数据
const specimens = ref([]);

// 是否正在加载更多
const isLoading = ref(false);

// 是否有更多数据
const hasMore = ref(true);

// 是否正在下拉刷新
const isRefreshing = ref(false);

// 路由参数
const type = ref("");

// 获取展览区分类数据请求参数
const queryparams = ref({
	galleryId: 1,
	page: 1
})

// 改变分类
const changeCategory = (categoryId) => {
  if (activeCategory.value === categoryId) return;
  activeCategory.value = categoryId;

  // 重置数据和分页
  specimens.value = [];
  queryparams.value.page = 1;
  queryparams.value.galleryId = categoryId;
  hasMore.value = true;

  // 加载该分类的数据
  loadSpecimens();
};

// 下拉刷新相关方法
const onPulling = () => {
  console.log("下拉刷新中...");
};

const onRefresh = () => {
  isRefreshing.value = true;

  // 重置数据和分页
  specimens.value = [];
  queryparams.value.page = 1;
  hasMore.value = true;

  // 加载该分类的数据
  loadSpecimens().then(() => {
    isRefreshing.value = false;
  });
};

const onRestore = () => {
  console.log("下拉刷新结束");
};

const onAbort = () => {
  console.log("下拉刷新中断");
};

// 加载更多数据
const loadMore = () => {
  if (isLoading.value || !hasMore.value) return;

  queryparams.value.page++;
  loadSpecimens();
};

// 加载标本数据
const loadSpecimens = async () => {
  isLoading.value = true;
  
  let moreData = [];
  
	const res = await reqExhibits(queryparams.value)
	isLoading.value = false;
	
	if (!res.data) {
	  uni.showToast({
	    title: '加载失败',
	    icon: "error"
	  })
	  return
	}
	
	moreData = res.data
	  
  if (moreData.length < 10) {
	  hasMore.value = false
  }
  
  // 追加数据
  specimens.value = [...specimens.value, ...moreData];
};

// 跳转到详情页
const navigateToDetail = (item) => {
  uni.navigateTo({
    url: `/pages/exhibition/detail?data=${encodeURIComponent(JSON.stringify(item))}`,
  });
  // setTimeout(() => {
	 // uni.$emit('getDetail', item) 
  // }, 100)
  
};

// 显示筛选弹窗
const showFilter = () => {
  uni.showToast({
    title: "筛选功能开发中",
    icon: "none",
  });
};

// 页面加载
onMounted(() => {
  // 获取路由参数
  const query = uni.getLaunchOptionsSync().query || {};
  if (query.type) {
    type.value = query.type;

    // 根据参数设置默认分类
    switch (type.value) {
      case "human":
        activeCategory.value = 1;
        break;
      case "pathology":
        activeCategory.value = 2;
        break;
      case "3d":
        // 暂时还是显示全部，实际可以添加3D类别
        activeCategory.value = 1;
        break;
    }
  }

  // 加载数据
  loadSpecimens();
});

// 监听分类变化，重新加载数据
watch(activeCategory, () => {
  // 在分类切换时，自动滚动到顶部
  setTimeout(() => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 300,
    });
  }, 100);
});

onMounted(async () => {
	const data = await reqGalleries()
	console.log(data)
	categories.value = data.data
	const res = await reqExhibits(queryparams.value)
	console.log(res)
	specimens.value = res.data
})
</script>

<style lang="scss" scoped>
.exhibition-page {
  background-color: $uni-bg-color-grey;
  min-height: 100vh;
}

// 分类筛选栏
.category-filter {
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  z-index: $zindex-dropdown;
  background-color: $uni-bg-color;
  padding: $spacer-2 0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.category-scroll {
  white-space: nowrap;
  width: 100%;
}

.category-item {
  display: inline-block;
  padding: $spacer-2 $spacer-4;
  margin: 0 $spacer-2;
  font-size: $uni-font-size-base;
  color: $uni-text-color-grey;
  position: relative;
  transition: all 0.3s;

  &.active {
    color: $uni-color-primary;
    font-weight: 500;

    &::after {
      content: "";
      position: absolute;
      left: 50%;
      bottom: -$spacer-1;
      transform: translateX(-50%);
      width: 40rpx;
      height: 4rpx;
      background: $gradient-primary;
      border-radius: 2rpx;
    }
  }

  &:first-child {
    margin-left: $spacer-4;
  }

  &:last-child {
    margin-right: $spacer-4;
  }
}

// 标本列表
.specimen-list {
  height: calc(100vh - 44px - var(--status-bar-height) - 100rpx);
  overflow: hidden;
}

.specimen-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: $spacer-3;
  padding: $spacer-4;
}

.specimen-card {
  background-color: $uni-bg-color;
  border-radius: $uni-border-radius-base;
  overflow: hidden;
  box-shadow: $box-shadow-card;
  transition: transform 0.3s;

  &:active {
    transform: scale(0.98);
  }
}

.specimen-image {
  width: 100%;
  height: 150px;
  object-fit: contain;
}

.specimen-info {
  padding: $spacer-3;
}

.specimen-title {
  font-size: $uni-font-size-base;
  font-weight: 500;
  margin-bottom: $spacer-1;
  display: block;
}

.specimen-desc {
  font-size: $uni-font-size-sm;
  color: $uni-text-color-grey;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

// 加载状态
.loading-state {
  text-align: center;
  padding: $spacer-4 0;
  color: $uni-text-color-grey;
  font-size: $uni-font-size-sm;
}

// 悬浮筛选按钮
.floating-btn {
  position: fixed;
  right: $spacer-4;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: $gradient-primary;
  box-shadow: $box-shadow-hover;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: $zindex-fixed;
}
</style>
